<template>
  <div>
    <el-form ref="deptForm" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <!--
          value: 对应的值，选项选中，值会保存到v-model中
          label: 显示出来的文字
        -->
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />

        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isedit: {
      type: Boolean,
      require: true
    },
    originLis: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      // const originList = this.originList
      const { originLis, isedit, id } = this
      // console.log('当前校验的值是', value)
      // console.log('校验参考的数据是', this.originList)
      // 判断思路
      // originList ==>[{id,pid,code,name},{id,pid,code,name}]
      // codeList  -->[code,                code]
      // 如果在 originList中找了code为value，说明验证不通过

      // 添加
      let codeList = originLis.map(it => it.code)
      // console.log('校验参考的数据是', codeList)

      if (isedit) { // 对编辑的特殊处理
        codeList = originLis.filter(it => it.id !== id).map(it => it.code)
        console.log(codeList)
      }

      // if (codeList.includes(value)) {
      //   callback(new Error(value + '被占用了'))
      // } else {
      //   callback()
      // }
      codeList.includes(value)
        ? callback(new Error(value + '被占用了'))
        : callback()
    }
    // 规则： 同级不重复
    const validName = (rule, value, callback) => {
      console.log('当前校验的名称是', value)
      // 在某个部门上点击 添加 时， 被占用的名字列表 = 这个部门的子部门
      //  ==>[{id,pid,code,name},{id,pid,code,name}]
      // 在orginList中找 pid=this.id 的对象 ==== 找到了子部门
      let nameList = this.originLis.filter(it => it.pid === this.id).map(it => it.name)
      console.log('找到了子部门', nameList)

      if (this.isedit) {
        // `在某个部门上点击**编辑**时：被占用的名字列表 = 当前部门的兄弟部门 - 它自己的名字`
        const obj = this.originLis.find(it => it.id === this.id)
        const pid = obj.pid
        // 当前部门的兄弟部门 - 它自己的名字
        nameList = this.originLis.filter(it => it.pid === pid && it.id !== this.id).map(it => it.name)
        // console.log('当前正编辑的对象', obj, arr1)
      }
      // if (value在被占用的名字中) {
      if (nameList.includes(value)) {
        callback(new Error(value + '被占用了'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [], // 部门负责人的名字列表
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    // 发请求
    // this.Employess()
    this.getEmployess()
    console.log(this.originLis, '555')
  },

  methods: {
    async getEmployess() {
      const res = await getEmployeeSimple()
      console.log('res', res)
      this.employees = res.data
    },
    hCancel() {
      this.$emit('close')
    },
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log('添加的结果是', res)
        // 告诉父组件，操作成功
        if (res.success) {
          this.$emit('success')
        }
      } catch (err) {
        console.log('err', err)
      }
    },
    // 获取部门信息
    async loadDetail() {
      if (this.isedit) {
        // alert('现在是编辑，要去获取详情')
        const res = await getDepartDetail(this.id)
        console.log('现在是编辑，要去获取详情', res)
        this.form = res.data
      } else {
        this.form = {
          name: '', // 部门名称
          code: '', // 部门编码
          manager: '', // 部门管理者
          introduce: '' // 部门介绍
        }
      }
    },
    async doEdit() {
      try {
        await updateDepartments(this.form)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('success')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    hSubmit() {
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          // 通过了
          // 2. 做添加或者编辑
          this.isedit ? this.doEdit() : this.doAdd()
        }
      })
    }
  }
}
</script>
